package cn.actoncode.boot.framework.common.http;

import cn.actoncode.boot.framework.common.exception.PlatformError;
import cn.actoncode.boot.framework.common.exception.ServiceErrorException;
import cn.actoncode.boot.framework.common.http.apache.ApacheRoutineUEPostRequestExecutor;
import cn.actoncode.boot.framework.common.http.enums.PlatformType;
import cn.actoncode.boot.framework.common.http.okhttp.OkHttpRoutineUEPostRequestExecutor;
import com.fasterxml.jackson.databind.node.ObjectNode;

import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Map;

/**
 * 常规的POST请求执行器，请求的参数是String, 返回的结果为ObjectNode
 * 由于有些平台返回的数据体会封装一层，所以用ObjectNode接收，不需要在解析完状态码之后再解析一遍数据体
 *
 * @author bin
 */
public abstract class RoutineUEPostRequestExecutor<H, P> implements RequestExecutor<ObjectNode, Map<String, String>> {
    protected RequestHttp<H, P> requestHttp;

    public RoutineUEPostRequestExecutor(RequestHttp requestHttp) {
        this.requestHttp = requestHttp;
    }

    @Override
    public void execute(String uri, Map<String, String> headers, Map<String, String> data, ResponseHandler<ObjectNode> handler, PlatformType platformType) throws ServiceErrorException, IOException {
        handler.handle(this.execute(uri, headers, data, platformType));
    }

    public static RequestExecutor<ObjectNode, Map<String, String>> create(RequestHttp requestHttp) {
        switch (requestHttp.getRequestType()) {
            case APACHE_HTTP:
                return new ApacheRoutineUEPostRequestExecutor(requestHttp);
            case OK_HTTP:
                return new OkHttpRoutineUEPostRequestExecutor(requestHttp);
            default:
                throw new IllegalArgumentException("非法请求参数");
        }
    }

    @NotNull
    public ObjectNode handleResponse(PlatformType platformType, String responseContent) throws ServiceErrorException {
        PlatformError platformError = PlatformError.parse(responseContent, platformType);
        if (platformError.getErrorCode() != platformType.getCode()) {
            throw new ServiceErrorException(platformError);
        }
        return platformError.getData();
    }
}
